package net.crowtheries.wirelessrouting;

import net.crowtheries.wirelessrouting.utils.Packet;
import net.crowtheries.wirelessrouting.utils.UDPSegment;
import ptolemy.actor.Director;
import ptolemy.actor.TypedAtomicActor;
import ptolemy.data.DoubleToken;
import ptolemy.data.IntToken;
import ptolemy.data.RecordToken;
import ptolemy.data.StringToken;
import ptolemy.data.Token;
import ptolemy.data.expr.Parameter;
import ptolemy.data.expr.StringParameter;
import ptolemy.data.type.BaseType;
import ptolemy.domains.wireless.kernel.WirelessIOPort;
import ptolemy.kernel.CompositeEntity;
import ptolemy.kernel.util.IllegalActionException;
import ptolemy.kernel.util.NameDuplicationException;

public class DataPacketGenerator extends TypedAtomicActor {
	public DataPacketGenerator(CompositeEntity container, String name)
			throws IllegalActionException, NameDuplicationException {
		super(container, name);
		output = new WirelessIOPort(this, "output", false, true);
		firingPeriod = new Parameter(this, "firingPeriod");
		firingPeriod.setExpression("0.1");
		firingPeriod.setTypeEquals(BaseType.DOUBLE);

		repeatCount = new Parameter(this, "repeatCount");
		repeatCount.setExpression("1");
		repeatCount.setTypeEquals(BaseType.INT);
		
		dstNode = new Parameter(this, "dstNode");
		dstNode.setExpression("1");
		dstNode.setTypeEquals(BaseType.STRING);
	}

	WirelessIOPort output;
	/**
	 * The period at which this actor will execute. This is a double with a
	 * default value of 0.1.
	 */
	public Parameter firingPeriod;
	public Parameter repeatCount;
	public Parameter dstNode;

	public void fire() throws IllegalActionException {
		if (_count > 0) {
			super.fire();
			String DSTNODE=((StringToken)dstNode.getToken()).stringValue();
			double firingPeriodValue = ((DoubleToken) firingPeriod.getToken())
					.doubleValue();
			Director director = getDirector();
			director.fireAt(this, director.getModelTime()
					.add(firingPeriodValue));

			RecordToken data = new RecordToken(new String[] { "DSTNODE",
					"Message" }, new Token[] { new StringToken(DSTNODE),
					new StringToken("message blabla") });
			
			UDPSegment udpSeg = new UDPSegment(21, 21, data);
			Packet packet = new Packet(DSTNODE, _localIP, udpSeg);
			output.send(0, packet.getPacketToken());
			_count--;
		}
	}

	public void initialize() throws IllegalActionException {
		super.initialize();

		Director director = getDirector();
		director.fireAtCurrentTime(this);

		_count = ((IntToken) repeatCount.getToken()).intValue();
		StringParameter localip=(StringParameter)this.getContainer().getAttribute("localIP");
		_localIP=localip.stringValue();
	}

	// /////////////////////////////////////////////////////////////////
	// // private members ////

	private int _count = 1;
	private String _localIP;

}
